package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.TravelComment;
import cn.wolfcode.luowowo.query.TravelCommentQuery;
import cn.wolfcode.luowowo.repository.TravelCommentRepository;
import cn.wolfcode.luowowo.service.IDestinationService;
import cn.wolfcode.luowowo.service.ITravelCommentService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
//@Transactional  暂时先别管事务
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private TravelCommentRepository repository;

    @Autowired
    private MongoTemplate template;

    public TravelComment get(String id) {
        Optional<TravelComment> optional = repository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    //查询出页面结果集
    public Page<TravelComment> query(TravelCommentQuery qo) {
        Query query = new Query();
        return DBHelper.query(template, TravelComment.class, query, qo.getPageable());
    }

    @Override
    public void save(TravelComment travelComment) {
        //如果是回复评论，会带有refcomment的id，查找出refcomment
        //再设置进travelcomment，最后执行保存操作
        travelComment.setId(null);
        travelComment.setCreateTime(new Date());
        String refId= travelComment.getRefComment().getId();
        Optional<TravelComment> op = repository.findById(refId);
        if(op.isPresent()){
            TravelComment refComment = op.get();
            travelComment.setRefComment(refComment);
        }
        repository.save(travelComment);
    }


    public void delete(String id) {
        repository.deleteById(id);
    }


    @Override
    public List<TravelComment> list() {
        return repository.findAll();
    }

    @Override
    public void update(TravelComment comment) {
        repository.save(comment);
    }

    @Override
    public List<TravelComment> queryComments(TravelCommentQuery qo) {
        if(StringUtils.hasLength(qo.getTravelId())) {
           return  repository.findByTravelId(qo.getTravelId());
        }
        return null;
    }

}
